﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.客户管理.WorkOrder;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.Work__CaigouOrderCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.Work__CaigouOrderHandler
{
    /// <summary>
    /// 采购订单创建命令处理
    /// </summary>
    public class Work__CaigouOrderCreateCommandHandler : IRequestHandler<Work__CaigouOrderCreateCommand, APIResult<object>>
    {
        /// <summary>
        /// 采购订单仓储
        /// </summary>
        private readonly IBaseRepository<Work_CaigouOrder> caigouRepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="caigouRepository">采购订单仓储</param>
        /// <param name="mapper">映射</param>
        public Work__CaigouOrderCreateCommandHandler(IBaseRepository<Work_CaigouOrder> caigouRepository,IMapper mapper)
        {
            this.caigouRepository = caigouRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public Task<APIResult<object>> Handle(Work__CaigouOrderCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<object> result = new APIResult<object>();

                DateTime date = DateTime.Now;
                string dateString = date.ToString("yyyyMMdd");
                string bianma = dateString;

                var obj = mapper.Map<Work_CaigouOrder>(request);

                obj.OrderCode = "CGDD" + bianma;
                obj.RukuStatu = "已完成入库";
                var r = caigouRepository.AddAsync(obj).Result;

                if (r > 0)
                {
                    result.Code = APIEnums.添加成功;
                    result.Msg = APIEnums.添加成功.ToString();
                    result.data = r;
                }
                else
                {
                    result.Code = APIEnums.添加失败;
                    result.Msg = APIEnums.添加失败.ToString();
                    result.data = r;
                }

                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
